import { reactive } from 'vue';
import apiService from '../services/apiService';

// 用户状态 - 使用 reactive 创建响应式对象
const state = reactive({
  user: null,
  isLoggedIn: false,
  token: null,
});

// 初始化状态（从 localStorage 恢复）
const initializeState = () => {
  const token = localStorage.getItem('jwt_token');
  const userInfo = localStorage.getItem('user_info');
  
  if (token && userInfo) {
    try {
      state.token = token;
      state.user = JSON.parse(userInfo);
      state.isLoggedIn = true;
      console.log('用户状态已从 localStorage 恢复:', state.user);
    } catch (error) {
      console.error('恢复用户状态失败:', error);
      localStorage.removeItem('jwt_token');
      localStorage.removeItem('user_info');
    }
  }
};

// 操作方法
const actions = {
  // 登录
  async login(username, password) {
    const response = await apiService.login(username, password);
    
    if (response.success && response.data) {
      state.token = response.data.token;
      state.user = response.data.user;
      state.isLoggedIn = true;
      
      // 保存到 localStorage
      localStorage.setItem('jwt_token', response.data.token);
      localStorage.setItem('user_info', JSON.stringify(response.data.user));
      
      console.log('登录成功，用户状态已更新:', state);
    }
    
    return response;
  },

  // 注册
  async register(userData) {
    console.log('📡 userStore.register 被调用，参数:', userData);
    const response = await apiService.register(userData);
    console.log('📡 注册API响应:', response);
    
    if (response.success && response.data) {
      // 注册成功后自动登录
      console.log('📡 开始自动登录...');
      const loginResponse = await apiService.login(userData.username, userData.password);
      console.log('📡 自动登录响应:', loginResponse);
      
      if (loginResponse.success && loginResponse.data) {
        state.token = loginResponse.data.token;
        state.user = loginResponse.data.user;
        state.isLoggedIn = true;
        
        // 保存到 localStorage
        localStorage.setItem('jwt_token', loginResponse.data.token);
        localStorage.setItem('user_info', JSON.stringify(loginResponse.data.user));
        
        console.log('注册并登录成功，用户状态已更新:', state);
      }
    }
    
    return response;
  },

  // 退出登录
  logout() {
    apiService.logout();
    state.user = null;
    state.token = null;
    state.isLoggedIn = false;
    
    // 清除 localStorage
    localStorage.removeItem('jwt_token');
    localStorage.removeItem('user_info');
    
    console.log('用户已退出登录');
  },

  // 更新用户信息
  async updateUser(userId, userData) {
    const response = await apiService.updateUser(userId, userData);
    
    if (response.success && response.data) {
      state.user = response.data;
      
      // 更新 localStorage
      localStorage.setItem('user_info', JSON.stringify(response.data));
      
      console.log('用户信息已更新:', state.user);
    }
    
    return response;
  },

  // 刷新用户信息
  async refreshUser() {
    if (!state.user?.id) return;
    
    try {
      const response = await apiService.getUserById(state.user.id);
      if (response.success && response.data) {
        state.user = response.data;
        localStorage.setItem('user_info', JSON.stringify(response.data));
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error);
    }
  },

  // 关联钱包地址
  async linkWallet(walletAddress) {
    if (!state.user?.id) {
      throw new Error('请先登录');
    }

    const response = await apiService.updateUser(state.user.id, {
      walletAddress,
    });

    if (response.success && response.data) {
      state.user = response.data;
      
      // 更新 localStorage
      localStorage.setItem('user_info', JSON.stringify(response.data));
      
      console.log('钱包已绑定:', walletAddress);
    }

    return response;
  },
};

// 初始化
initializeState();

// 导出 state 和 actions
export default {
  state,  // 直接导出 reactive state，而不是 readonly
  actions,
  // 为了向后兼容，保留 getters
  getters: {
    getUser: () => state.user,
    isLoggedIn: () => state.isLoggedIn,
    getToken: () => state.token,
    getWalletAddress: () => state.user?.walletAddress || null,
  },
};
